package com.zsy.service.Impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zsy.dao.EmployeeDao;
import com.zsy.pojo.Employee;
import com.zsy.pojo.Page;
import com.zsy.pojo.R;
import com.zsy.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public R<Employee> login(Employee employee) {

        Employee login = employeeDao.login(employee);
        //根据用户名没法找到用户
        if (login == null) {
            return R.error("用户名不存在");
        }
        //对比密码
        String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!md5Password.equals(login.getPassword())) {
            return R.error("密码错误");
        }
        //检查是否为禁用的用户
        if (login.getStatus() == 0) {
            return R.error("该用户已被禁用");
        }
        //登陆成功
        return R.success(login);
    }

    @Override
    public void save(Employee employee) {
        //用MD5加密密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置状态
        employee.setStatus(1);
        //设置时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //调用dao保存
        employeeDao.sace(employee);

    }

    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        //设置当前页和页面大小
        PageHelper.startPage(page, pageSize);
        //获取数据
        log.info(name);
        List<Employee> byName = employeeDao.findByName(name);
        //创建PageInfo对象，把List集合传入
        PageInfo<Employee> pageinfo = new PageInfo<>(byName);
        //把PageInfo的信息转入到Page对象
        Page<Employee> pageResult = new Page<>(pageinfo.getList(), pageinfo.getTotal(), pageinfo.getPageSize(), pageinfo.getPageNum());

        return pageResult;
    }

    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeDao.update(employee);
    }

    @Override

    public Employee findById(long id) {
        Employee byId = employeeDao.findById(id);
        return byId;
    }
}
